package com.pine.common.database.listener;

import com.pine.common.database.annotations.DataPermission;
import com.pine.common.database.constant.DbDataScopeEnum;
import com.pine.common.util.user.UserInfo;
import com.pine.common.util.user.UserUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.schema.Column;
import org.springframework.stereotype.Component;

/**
 * 处理仅自身权限范围
 *
 * @author pine manage
 * @since 2024-09-26
 */
@Component
public class ProcessOnlySelfDataScopeListener implements ProcessWhereExpressionListener {
    /**
     * 处理where条件
     *
     * @param where          where语句
     * @param dataPermission 权限注解
     * @param mainTableName  主表名/别名
     */
    @Override
    public Expression process(Expression where, DataPermission dataPermission, String mainTableName) {
        UserInfo userInfo = UserUtil.get();
        EqualsTo usesEqualsTo = new EqualsTo();
        usesEqualsTo.setLeftExpression(new Column(mainTableName + "." + dataPermission.permissionFieldName()));
        usesEqualsTo.setRightExpression(new LongValue(String.valueOf(userInfo.id())));
        return new AndExpression(where, usesEqualsTo);
    }

    /**
     * 获取数据权限范围
     *
     * @return 数据权限范围
     */
    @Override
    public DbDataScopeEnum getDataScope() {
        return DbDataScopeEnum.ONLY_SELF;
    }
}
